package com.china08.yxyapi.schedule.synresbase;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.entity.db.res.YxyResBook;
import com.china08.yxyapi.entity.db.res.YxyResBookContents;
import com.china08.yxyapi.entity.db.res.YxyResPhase;
import com.china08.yxyapi.entity.db.res.YxyResSemester;
import com.china08.yxyapi.entity.db.res.YxyResSubject;
import com.china08.yxyapi.entity.db.res.YxyResVersion;
import com.china08.yxyapi.entity.db.yxy.YxyQuesKnow;
import com.china08.yxyapi.model.ResModel;
import com.china08.yxyapi.repository.db.YxyQuesKnowRepository;
import com.china08.yxyapi.repository.db.YxyResBookContentsRepository;
import com.china08.yxyapi.repository.db.YxyResBookRepository;
import com.china08.yxyapi.repository.db.YxyResPhaseRepository;
import com.china08.yxyapi.repository.db.YxyResSemesterRepository;
import com.china08.yxyapi.repository.db.YxyResSubjectRepository;
import com.china08.yxyapi.repository.db.YxyResVersionRepository;
import com.china08.yxyapi.service.updateresource.QuesUpdateService;
import com.china08.yxyapi.service.updateresource.ResourceUpdateService;
import com.china08.yxyapi.service.updateresource.WeikeUpdateService;
import com.china08.yxyapi.util.YxyScheduleRunnableUtil;

@Profile(value = { "dev", "tes", "pro" })
@Component
@EnableScheduling
public class SynBaseDataTask {

    @Autowired
    private YxyResBookRepository yxyResBookRepository;

    @Autowired
    private YxyResSubjectRepository YxyResSubjectRepository;

    @Autowired
    private YxyResPhaseRepository yxyResPhaseRepository;

    @Autowired
    private YxyResVersionRepository YxyResVersionRepository;

    @Autowired
    private YxyResBookContentsRepository yxyResBookContentsRepository;

    @Autowired
    private YxyResSemesterRepository yxyResSemesterRepository;

    @Autowired
    private ResourceUpdateService rus;

    @Autowired
    private WeikeUpdateService wus;

    @Autowired
    private QuesUpdateService qus;

    @Autowired
    private YxyQuesKnowRepository yxyQuesKnowRepository;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${spring.profiles.active}")
    String profiles;

    // @Scheduled(fixedRate = 1000 * 60 * 1)
    @Scheduled(cron = "0 5 0 * * ?")
    public void task() throws UnknownHostException {

        // ##
        // 检测定时任务是否可执行
        if (!YxyScheduleRunnableUtil.checkRunnable()) { return; }

        restBookcontent();
        restKnow();
    }

    public boolean restKnow() {
        List<YxyQuesKnow> knowledges = yxyQuesKnowRepository.findByIsUpdate(1);
        if (knowledges.size() > 0) {
            RestKnowReqModel knowReqModel = new RestKnowReqModel();
            knowReqModel.knowledges = knowledges;
            wus.updateWeikeByKnowledges(knowledges);
            qus.updateQues(knowledges);
            if (StringUtils.equals("dev", profiles) || StringUtils.equals("test", profiles)) {
                for (YxyQuesKnow yxyResBookContents : knowledges) {
                    yxyResBookContents.setIsUpdate(0);
                }
                yxyQuesKnowRepository.save(knowledges);
            } else {
                ResModel respModel = restTemplate.postForObject("http://www.hrbeduy.com/api_yw/comm/updweikeandques",
                        knowReqModel, ResModel.class);
                if (StringUtils.equals(respModel.getEvent(), ResModel.EVENT_SUCCESS)) {
                    for (YxyQuesKnow yxyResBookContents : knowledges) {
                        yxyResBookContents.setIsUpdate(0);
                    }
                    yxyQuesKnowRepository.save(knowledges);
                }
            }
            return false;
        }
        return true;
    }

    public boolean restBookcontent() {
        List<YxyResBookContents> bookContents = yxyResBookContentsRepository.findByIsUpdate(1);
        if (bookContents.size() > 0) {
            List<YxyResBook> books = new ArrayList<YxyResBook>();
            List<YxyResSubject> subjects = new ArrayList<YxyResSubject>();
            List<YxyResPhase> phases = new ArrayList<YxyResPhase>();
            List<YxyResVersion> versions = new ArrayList<YxyResVersion>();
            List<YxyResSemester> semesters = new ArrayList<YxyResSemester>();
            Set<String> bookIds = bookContents.stream().map(x -> x.getBookId()).collect(Collectors.toSet());
            books = yxyResBookRepository.findByIdIn(bookIds);
            Set<String> phaseIds = books.stream().map(x -> x.getPhaseId()).collect(Collectors.toSet());
            phases = yxyResPhaseRepository.findByIdIn(phaseIds);
            Set<String> subjectIds = books.stream().map(x -> x.getSubjectId()).collect(Collectors.toSet());
            subjects = YxyResSubjectRepository.findByIdIn(subjectIds);
            Set<String> versionIds = books.stream().map(x -> x.getVersionId()).collect(Collectors.toSet());
            versions = YxyResVersionRepository.findByIdIn(versionIds);
            Set<String> semesterIds = books.stream().map(x -> x.getSemersterId()).collect(Collectors.toSet());
            semesters = yxyResSemesterRepository.findByIdIn(semesterIds);
            rus.updateResourceByBookcontentId(bookContents);
            RestReqModel model = new RestReqModel();
            model.phases = phases;
            model.subjects = subjects;
            model.versions = versions;
            model.books = books;
            model.semesters = semesters;
            model.bookContents = bookContents;
            if (StringUtils.equals("dev", profiles) || StringUtils.equals("test", profiles)) {
                // for (YxyResBookContents yxyResBookContents : bookContents) {
                // yxyResBookContents.setIsUpdate(0);
                // }
                // yxyResBookContentsRepository.save(bookContents);
            } else {
                restTemplate.postForObject("http://www.hrbeduy.com/api_yw/comm/updateresource", model, ResModel.class);
            }

            return false;
        }
        return true;
    }

    protected static class RestReqModel {
        public List<YxyResPhase> phases;
        public List<YxyResSubject> subjects;
        public List<YxyResVersion> versions;
        public List<YxyResBook> books;
        public List<YxyResSemester> semesters;
        public List<YxyResBookContents> bookContents;
    }

    protected static class RestKnowReqModel {
        public List<YxyQuesKnow> knowledges;
    }
}
